package router

import (
	"context"
	"errors"
	"github.com/cn-ygf/go-admin/internal/modular/system"
	"github.com/cn-ygf/go-admin/pkg/config"
	"github.com/cn-ygf/go-admin/pkg/log"
	"github.com/go-playground/validator/v10"
	"github.com/kataras/golog"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/kataras/iris/v12/mvc"
	"time"
)

var (
	httpLog = log.NamedLogger("router")
)

const (
	DefaultHTTPTimeout = time.Minute
)

// Server 管理接口提供
type Server struct {
	Application *iris.Application
	Cleanup     func()
}

// StartListener 启动服务器
func StartListener() (*Server, error) {
	addr := config.GetString("server.addr")
	httpLog.Infof("Starting api server listener on '%s'", addr)
	server := &Server{}
	server.router()

	server.Cleanup = func() {
		ctx, cancelHTTP := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancelHTTP()
		//if err := server.HTTPServer.Shutdown(ctx); err != nil {
		//	httpLog.Warnf("Failed to shutdown api server")
		//}
		if err := server.Application.Shutdown(ctx); err != nil {
			httpLog.Warnf("Failed to shutdown api server")
		}

	}

	go func() {
		err := server.Application.Run(iris.Addr(addr))
		if err != nil {
			httpLog.Errorf("Start api server failed on '%s'", addr)
			httpLog.Errorln(err)
			return
		}
	}()

	return server, nil
}

func (s *Server) router() {
	isDev := config.GetBool("server.dev")
	path := config.GetString("server.path")
	app := iris.New()
	app.Use(recover.New())
	app.Use(logger.New())
	if isDev {
		app.Logger().Level = golog.DebugLevel
	}
	app.Validator = validator.New()
	v1 := app.Party(path)
	m := mvc.New(v1)
	m.HandleError(func(ctx iris.Context, err error) {
		var validationErrors validator.ValidationErrors
		ok := errors.As(err, &validationErrors)
		if ok {
			_ = ctx.StopWithJSON(200, map[string]any{
				"code": 600,
				"msg":  "参数错误",
			})
			return
		}

	})
	system.Router(m)

	s.Application = app
}
